<template>
  <div class="team-management">
    <!-- 搜索和添加按钮 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="小组名称"
        style="width: 200px"
        clearable
      >
        <el-button slot="append" @click="searchTeam">查询</el-button>
      </el-input>
      <el-button type="primary" @click="showAddMemberForm = true">添加人员</el-button>
    </div>

    <!-- 团队列表表格 -->
    <el-table
      :data="filteredTeams"
      stripe
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="序号" width="80"></el-table-column>
      <el-table-column prop="name" label="小组名称"></el-table-column>
      <el-table-column prop="num" label="成员数量" width="100"></el-table-column>
      <el-table-column prop="integral" label="积分" width="100"></el-table-column>
      <el-table-column prop="slogan" label="口号"></el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="showTeamMembers(scope.row.id)"
          >
            查看成员
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 成员列表对话框 -->
    <el-dialog title="小组成员" :visible.sync="showMembersDialog" width="50%">
      <el-table :data="currentTeamMembers">
        <el-table-column prop="nickName" label="姓名"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="age" label="年龄" width="80"></el-table-column>
      </el-table>
    </el-dialog>

    <!-- 添加成员表单 -->
    <el-dialog title="添加成员" :visible.sync="showAddMemberForm" width="30%">
      <el-form :model="newMember" :rules="rules" ref="memberForm" label-width="80px">
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="newMember.nickName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="newMember.gender" placeholder="请选择">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="newMember.age" :min="1" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="所属小组" prop="squadId">
          <el-select v-model="newMember.squadId" placeholder="请选择">
            <el-option
              v-for="team in teams"
              :key="team.id"
              :label="team.name"
              :value="team.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddMemberForm = false">取 消</el-button>
        <el-button type="primary" @click="addMember">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SquadApi from '@/api/Squad.vue'
import UserApi from '@/api/User.vue'

export default {
  name: 'TeamManagement',
  data() {
    return {
      teams: [],
      searchText: '',
      loading: false,
      showAddMemberForm: false,
      showMembersDialog: false,
      currentTeamMembers: [],
      newMember: {
        nickName: '',
        gender: '',
        age: null,
        squadId: ''
      },
      rules: {
        nickName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' }
        ],
        squadId: [
          { required: true, message: '请选择小组', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    filteredTeams() {
      if (!this.searchText) return this.teams
      return this.teams.filter(team =>
        team.name.toLowerCase().includes(this.searchText.toLowerCase())
      )
    }
  },
  methods: {
    // 获取所有团队
    async fetchTeams() {
      this.loading = true;
      try {
        const data = await SquadApi.listSquads();
        console.log('获取到的团队数据:', data); // 添加这行调试日志
        this.teams = data.map(team => ({
          id: team.id,
          name: team.name,
          num: team.num || 0,
          integral: team.integral || 0,
          slogan: team.slogan || ''
        }));
      } catch (error) {
        console.error('获取团队列表失败:', error); // 详细记录错误
        this.$message.error('获取团队列表失败');
      } finally {
        this.loading = false;
      }
    },
    async showTeamMembers(squadId) {
      try {
        const data = await UserApi.getUsersBySquadId(squadId)
        this.currentTeamMembers = data
        this.showMembersDialog = true
      } catch (error) {
        this.$message.error('获取成员列表失败')
      }
    },

    // 添加成员
    async addMember() {
      try {
        await this.$refs.memberForm.validate()
        const result = await UserApi.addUser({
          nickName: this.newMember.nickName,
          gender: this.newMember.gender,
          age: parseInt(this.newMember.age),
          squadId: parseInt(this.newMember.squadId)
        })

        if (result) {
          this.$message.success('添加成员成功')
          this.showAddMemberForm = false
          this.resetMemberForm()
          await this.fetchTeams()
        }
      } catch (error) {
        this.$message.error('添加成员失败')
      }
    },

    resetMemberForm() {
      if (this.$refs.memberForm) {
        this.$refs.memberForm.resetFields()
      }
      this.newMember = {
        name: '',
        gender: '',
        age: null,
        squadId: ''
      }
    },

    searchTeam() {
      // 使用computed属性自动过滤，这里可以为空
      console.log('搜索关键词:', this.searchText)
    }
  },
  created() {
    this.fetchTeams()
  }
}
</script>

<style scoped>
.team-management {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}
</style> 